package com.coocaa.x.app.hall.web;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.coocaa.x.app.hall.R;
import com.coocaa.x.app.hall.view.widget.TipToast;
import com.coocaa.x.app.hall.web.HallWebViewChromeClient.WebChromeClientListener;
import com.coocaa.x.app.hall.web.HallWebViewClient.WebviewClientListener;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;


/**
 * Created by luwei on 15-6-16.
 */
public class HallWebActivity extends Activity implements WebChromeClientListener, WebviewClientListener {

    private static final String tag = "hallweb";
    private Context mContext = null;
    private WebView mWebView = null;
    private LinearLayout webPageLayout; // 整体浏览器布局，包括webView和进度条两部分
    private LinearLayout progressLayout;
    private LinearLayout ll;
    private ImageView progressBody = null;
    private ImageView header = null;
    private int width = 0;
    private boolean isSubFrameLoading = true;
    private String url;
    private boolean isNeedPoint = true;

    //ipad5
    private static final String IPAD_USERAGENT =
            "Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) " +
                    "AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hallweb);
        initResolution();
        mContext = CoocaaApplication.getContext();
        webPageLayout = (LinearLayout) findViewById(R.id.webpage);
        progressLayout = (LinearLayout) findViewById(R.id.progresslayout);
        ll = (LinearLayout) findViewById(R.id.ll);
        initProgressBar();
        url = getUriFromIntent();
//        initView(url);
        ll.addView(initWebView(url));
    }

    private void initResolution() {
        Display display = ((WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        width = display.getWidth();
    }

    private void initProgressBar() {
        progressBody = new ImageView(mContext);
        header = new ImageView(mContext);
        progressBody.setBackgroundDrawable(mContext.getResources().getDrawable(
                R.drawable.progress_bar));
        header.setBackgroundDrawable(mContext.getResources().getDrawable(
                R.drawable.progress_head));
        progressLayout.addView(progressBody);
        progressLayout.addView(header);
    }

    private Handler progressHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            int progress = msg.what;
            LogUtils.d(tag, "progressHandler---isSubFrameLoading:" + isSubFrameLoading + " " + progress);
            if (isSubFrameLoading) {
                progressLayout.setVisibility(View.VISIBLE);
                progressBody
                        .setLayoutParams(new LinearLayout.LayoutParams(
                                (progress - 5) * width / 100,
                                ViewGroup.LayoutParams.FILL_PARENT));
                header.setLayoutParams(new LinearLayout.LayoutParams(
                        5 * width / 100, ViewGroup.LayoutParams.FILL_PARENT));
                progressLayout.postInvalidate();
            }

            if (progress == 100 && isNeedPoint) {
                LogUtils.d(tag, "onProgressChanged----100--");
                isNeedPoint = false;
                progressLayout.setVisibility(View.GONE);
                CoocaaApplication.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            XServiceManager.getLiteCCConnectorService().startWebPoints(url);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    };

    private String getUriFromIntent() {
        Uri uri = getIntent().getData();
        if (uri != null && !uri.toString().equals(""))
            return uri.toString();
        TipToast.getInstance().showToast("访问的网站地址为空！");
        return "";
    }

//    ProgressBar pb;
//    LinearLayout progress_layout;
//    private View getPBar(){
//        LayoutInflater inflater = getLayoutInflater();
//        View view = inflater.inflate(R.layout.progress, null);
//        progress_layout = (LinearLayout)view.findViewById(R.id.progress_layout);
//        pb = (ProgressBar) view.findViewById(R.id.myProgressBar);
//        pb.setProgress(10);
//        return  view;
//    }

    private WebView initWebView(String url) {
        if (mWebView == null) {
            mWebView = new WebView(mContext);
            mWebView.setLayoutParams(new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT,
                    LinearLayout.LayoutParams.FILL_PARENT));
            WebSettings ws = mWebView.getSettings();
            ws.setJavaScriptEnabled(true);
            ws.setUseWideViewPort(true);
            ws.setLoadWithOverviewMode(true);
            ws.setDomStorageEnabled(true);
            ws.setUserAgentString(IPAD_USERAGENT);
            mWebView.setWebChromeClient(new HallWebViewChromeClient(HallWebActivity.this));
            mWebView.setWebViewClient(new HallWebViewClient(HallWebActivity.this));
        }
        mWebView.loadUrl(url);
        mWebView.requestFocus();
        return mWebView;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mWebView = null;
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mWebView != null && mWebView.canGoBack()) {
                mWebView.goBack();
            } else {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onProgressChanged(WebView view, int newProgress) {
//        if(newProgress > 95){
//            progress_layout.setVisibility(View.GONE);
//        }else if(newProgress > 40){
//            progress_layout.setVisibility(View.VISIBLE);
//            pb.setProgress(newProgress);
//        }

        if (newProgress >= 35) {
            LogUtils.d(tag, "onProgressChanged  progress:" + newProgress);
            Message msg = new Message();
            msg.what = newProgress;
            progressHandler.sendMessage(msg);
        }

    }

    @Override
    public void onReceiverTitle(WebView view, String title) {

    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        isSubFrameLoading = true;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        isSubFrameLoading = false;
    }
}
